<template>
  <div>
    <!--数据列表-->
    <div class="table-container">
      <vxe-grid ref='lineListPLxGrid' v-bind="gridOptions"  size="mini" :loading="listLoading">
        <template #form>
          <div>
            <!--搜索-->
            <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
              <el-form-item label="客户名称：">
                <el-select
                  clearable
                  v-model="listQuery.customerId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="querySearch">
                  <el-option
                    v-for="item in querySearchList"
                    :key="item.customerId"
                    :label="item.customerName"
                    :value="item.customerId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="最新跟进时间：">
                <el-date-picker
                  v-model="listQuery.cglTrackingTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="未跟进天数：">
                <el-select v-model="listQuery.cglTrackingTimeType" clearable>
                    <el-option value="sevenDaysMore" label="超7天"></el-option>
                    <el-option value="fifteenDaysMore" label="超15天"></el-option>
                    <el-option value="thirtyDaysMore" label="超30天"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="最新成交时间：">
                <el-date-picker
                  v-model="listQuery.cglOrderTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="未成交天数：">
                <el-select v-model="listQuery.cglOrderTimeType" clearable>
                  <el-option value="sevenDaysMore" label="超7天"></el-option>
                  <el-option value="fifteenDaysMore" label="超15天"></el-option>
                  <el-option value="thirtyDays" label="超30天"></el-option>
                  <el-option value="thirtyDaysMore" label="超60天"></el-option>
                  <el-option value="ninetyDaysMore" label="超90天"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="产品线：">
                <el-select v-model="listQuery.goodsLineId" filterable clearable>
                  <el-option :label="item.cddValue" v-for="item in goodsLineList" :value="item.cddId" :key="item.cddId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="负责日期：">
                <el-date-picker
                  v-model="listQuery.cglMyChargeTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="创建时间：">
                <el-date-picker
                  v-model="listQuery.cglCreateTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="排序：">
                <el-select v-model="listQuery.sort"  placeholder="请选择" clearable>
                  <el-option key="1" label="最新跟进时间倒序" value="1"></el-option>
                  <el-option key="2" label="最新跟进时间升序" value="2"></el-option>
                  <el-option key="3" label="最新成交时间倒序" value="3"></el-option>
                  <el-option key="4" label="最新成交时间升序" value="4"></el-option>
                  <el-option key="5" label="成交量升序" value="5"></el-option>
                  <el-option key="6" label="成交量倒序" value="6"></el-option>
                  <el-option key="7" label="持有时间倒序" value="7"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="负责人：" v-if="listQuery.tab != 'myCharge'">
                <el-select v-model="listQuery.chargeId"  placeholder="请选择" clearable filterable>
                  <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户标签：">
                <el-select v-model="listQuery.cglCustomerLabel" filterable placeholder="请选择" clearable multiple>
                    <el-option :label="item.name" :value="item.tagId" :key="item.tagId" v-for="item in labels"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="目标开发阶段：">
                <el-select v-model="listQuery.cglTargetDevelopState"  placeholder="请选择" clearable>
                  <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in developSteps" v-if="item.id > 0"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="阶段更新时间：">
                <el-date-picker
                  v-model="listQuery.cglDevelopChangeTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="是否设置目标：">
                <el-select v-model="listQuery.isTarget"  placeholder="请选择" clearable>
                  <el-option label="是" :value="1" ></el-option>
                  <el-option label="否" :value="2" ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="目标状态：">
                <el-select v-model="listQuery.devState"  placeholder="请选择" clearable>
                  <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in devStates"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="是否为共享池：" v-if="listQuery.tab == 'myCharge'">
                <el-select v-model="listQuery.isResource"  placeholder="请选择" clearable>
                  <el-option label="是" :value="1" :key="1"></el-option>
                  <el-option label="否" :value="0" :key="0"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="是否成交：">
                <el-select v-model="listQuery.isDeal"  placeholder="请选择" clearable>
                  <el-option label="是" :value="1" ></el-option>
                  <el-option label="否" :value="0" ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button
                  @click="handleSearchList()"
                  type="primary">
                  查询
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>

        </template>
        <template #toolbar_buttons>
          <div style="padding:0 0 10px 0">
            <span>合计主客户数：{{ customerCount }}个</span>
            <span style="padding-left:20px">产品线数：{{ goodsLineCount }}个</span>
            <span style="padding-left:20px" v-if="listQuery.tab == 'myCharge'">共享池客户：{{ resourceNum }}个</span>
          </div>
          <el-button type="primary" size="small" @click="toAdd" v-if="listQuery.tab == 'myCharge'">新增客户</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="moveLine('resource')">转移共享池</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="moveLine('share')">设置共享</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="moveLine('delete')">移入回收站</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="moveLine('public')">转入公海</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="showPop">增加标签</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="showDevPop('more','')">批量设置开发目标</el-button>
          <el-button type="primary" size="small" v-if="listQuery.tab == 'myCharge'" @click="downloadExcel()" :loading="btnLoading6">导出产品线目标数据</el-button>
          <el-button type="success" size="small" v-if="listQuery.tab == 'myCharge'" @click="showImport()">导入产品线目标数据</el-button>
          <el-button type="primary" size="small" @click="moveLine('user')" v-if="listQuery.tab == 'myCharge'">转移</el-button>

<!--          <el-button type="primary" size="small" v-if="listQuery.tab == 'share' || listQuery.tab == 'department'" @click="showPop4">添加备注</el-button>-->

          <div style="margin:10px 0">
              <el-radio-group v-model="listQuery.cglCurrentDevelopState" @change="handleSearchList" size="small">
                <el-radio-button :label="item.id" v-for="(item,index) in developSteps" :key="item.id">
                  {{ item.name }} <span><span v-if="index > 0">{{numCount[index-1] ? '('+numCount[index-1]+')' : ''}}</span></span>
                </el-radio-button>
              </el-radio-group>
          </div>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <div @click="toDetail(row)" type="primary"  style="font-size:12px;vertical-align: middle;cursor:pointer;text-align: center;color:#409EFF">
              <div>{{row.customerName}}</div>
              <div>{{row.kingNumber}}</div>
          </div>
        </template>

        <template #num2_default="{ row, rowIndex }">
            <span v-for="item in row.relationCustomers" style="padding-left:10px">{{item.customerName}}</span>
        </template>

        <template #num3_default="{ row, rowIndex }">
          <el-button style="margin-right:10px;" type="text" size="small"  @click="showAddgj(row)" v-if="listQuery.tab=='myCharge'">增加跟进</el-button>

          <el-button style="margin-right:10px;" type="text" size="small" v-if="listQuery.tab == 'myCharge'" @click="showDevPop('one',row)">设置开发目标</el-button>
          <el-dropdown trigger="click" size="mini" v-if="listQuery.tab=='myCharge'">
              <span class="el-dropdown-link" style="cursor: pointer;color: #409EFF;font-size:12px">更多 <i class="el-icon-arrow-down el-icon--right"></i></span>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item>
                  <el-button style="margin-right:10px;" type="text" size="small" @click="showPop2(row)">跟进记录</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button style="margin-right:10px;" type="text" size="small"  @click="showPop3(row)">联系人</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="listQuery.tab == 'myCharge'">
                  <el-button style="margin-right:10px;" type="text" size="small"  @click="moveLine('user','one',row)">转移</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="listQuery.tab == 'myCharge'">
                  <el-button style="margin-right:10px;" type="text" size="small"  @click="showAddLxr('hasCglid',row)">增加联系人</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
          </el-dropdown>
          <el-button style="margin-right:10px;" type="text" size="small" @click="showPop2(row)" v-if="listQuery.tab!='myCharge'">跟进记录</el-button>
<!--          <el-button style="margin-right:10px;" type="text" size="small"  @click="showPop3(row)" v-if="listQuery.tab!='myCharge'">联系人</el-button>-->
        </template>
      </vxe-grid>
    </div>
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="dialogVisible" width="500px">
      <el-form  :model="form" size="mini" label-width="100px" ref="form" :rules="rules">
        <div style="padding-bottom:20px;">{{popcon}}</div>
        <el-form-item label="转移到：" prop="target" v-if="popType=='user'">
          <el-select v-model="form.target" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="共享人：" v-if="popType == 'share'" prop="target">
          <el-select v-model="form.target" filterable multiple placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" label-width="80px" v-if="popType == 'delete' || popType == 'public' || popType=='resource'" prop="remark">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="添加标签" :visible.sync="dialogVisible2" width="800px" >
      <el-form :model="form2" size="mini" label-width="0px" ref="form2" :rules="rules2">
          <el-form-item prop="tagIds">
             <div style="max-height: 500px;overflow-y: auto">
               <el-checkbox-group v-model="form2.tagIds">
                 <div style="margin-bottom:20px;" v-for="item in tags" :key="item.typeId">
                   <div style="font-weight: bold;font-size:14px;margin-bottom:5px;">{{item.typeName}}</div>
                   <div class="type-list">
                     <el-checkbox :label="ee.tagId" border size="mini" v-for="ee in item.tag" :key="ee.tagId">{{ee.name}}</el-checkbox>
                   </div>
                 </div>
                 <div style="margin-bottom:20px;">
                   <div style="font-weight: bold;font-size:14px;margin-bottom:5px;">自定义标签  <el-button type="text" style="margin-left:20px" @click="addLabel">+ 添加自定义标签</el-button></div>
                   <div class="type-list">
                     <el-checkbox :label="ee.tagId" border size="mini" v-for="ee in myTags" :key="ee.tagId">{{ee.name}}</el-checkbox>
                   </div>
                 </div>
               </el-checkbox-group>
             </div>
          </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="新建自定义标签" :visible.sync="dialogVisible3" width="400px" >
      <el-form :model="form3" size="mini" ref="form3" :rules="rules3" label-width="80px">
        <el-form-item prop="name" label="标签名">
            <el-input v-model="form3.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible3 = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm3" :loading="btnLoading3">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog :close-on-click-modal="false" title="增加备注" :visible.sync="dialogVisible4" width="400px" :rules="rules4">
      <el-form  :model="form4" size="mini" label-width="100px" ref="form4">
        <el-form-item label="备注：" prop="remark">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form4.remark"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible4 = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :title="title5" :visible.sync="dialogVisible5" width="400px" :rules="rules5">
      <el-form :model="form5" size="mini" label-width="150px" ref="form5" :rules="rules5">
        <el-form-item label="本月目标阶段：" prop="cglTargetDevelopState">
           <el-select v-model="form5.cglTargetDevelopState">
               <el-option v-for="item in developSteps" :value="item.id" :label="item.name" :key="item.id" v-if="item.id > 0"></el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="本月目标有效跟进数："  prop="cglTargetTrackingNum">
           <el-input v-model="form5.cglTargetTrackingNum"></el-input>
        </el-form-item>
        <el-form-item label="预计开发完成时间：" v-if="popType5 != 'more'" prop="cglTargetFinishedDate">
          <el-date-picker
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            v-model="form5.cglTargetFinishedDate"
            style="display: inline-block;width:150px"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible5 = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm5" :loading="btnLoading5">确 定</el-button>
      </span>
    </el-dialog>

    <gjList ref="gjList"></gjList>
    <lxrList ref="lxrList"></lxrList>
    <addLxr ref="addLxr"></addLxr>
    <addGj ref="addGj" @getList="getList"></addGj>
    <addProgress ref="addProgress" @getSteps="getList"></addProgress>
    <import-pop ref="importPop" @getList="handleSearchList"></import-pop>

  </div>
</template>
<script>
import {getCustomerOption,getOrderUsersList,getAddressList,customerPotential,getCustomerSetting} from '@/api/partner'
import {goodsLineMyGoodsLine,productCustomersTagList,addCustomerTags,shareGoodsLine,deleteGoodsLine,commonGoodsLine,myAllTags,productCustomersAddTag,developBatchSetTarget,goodsLineMove} from '@/api/company'
import {formatDate} from '@/utils/date';
import gjList from './gjList';
import lxrList from './lxrList';
import addLxr from './addLxr';
import addGj from './addGj';
import addProgress from './addProgress';
import importPop from "./importPop";
import store from '@/store'
import { mapGetters } from 'vuex'

const defaultListQuery={
  tab:'',
  chargeId:'',
  'devState' :'',                 //目标状态 1逾期 2进行中 3已完成
  'cglCurrentDevelopState' :'',                 //当前开发阶段
  'cglTargetDevelopState'   :'',               //目标开发阶段
  'cglDevelopChangeTime' :[],                //阶段时间
  'isTarget'   :'',              //目标状态 1设置 2不设置
  isResource:'',
  isDeal:"",
  "isMainCustomer" : "", //(筛选主客户，1是)
  "customerId" : '', //客户筛选
  "goodsLineId" : '', //客户产品线筛选
  "cglMyChargeTime" : [], //负责日期
  "cglCreateTime" : [], //创建时间
  "cglCustomerLabel" : "", //客户标签,多个逗号隔开
  cglTrackingTime:[],//最新跟进时间
  cglOrderTime:[],//最新成交时间
  "cglTrackingTimeType" : "", //跟进时间时间类型(今天-today,7天内-sevenDays,超7天-sevenDaysMore,超15天-fifteenDaysMore，超30天-thirtyDaysMore)
  "cglOrderTimeType" : "", //最新成交时间类型(超7天-sevenDaysMore，超15天-fifteenDaysMore，超30天-thirtyDays,超60天-thirtyDaysMore，超90天-ninetyDaysMore)
  "sort" : "", //排序(排序(最近跟进时间-trackingTimeDesc,最近成交时间-cglOrderTime,最新跟进成交时间-trackingOrderTime,更进时间倒序-trackingTimeDesc))
};
const defaultForm = {
  cglIds:'',
  remark:'',
  target:''//移入公海，回收站 1 ，称出公海，回收站0
};

const defaultForm2 = {
  cglIds:'',
  tagIds:[]
};

const defaultForm3 = {
  type:2,
  name:''
};

const defaultForm4 = {
  cglIds:'',
  remark:''
};

const defaultForm5 = {
  "cglIds" : "", //产品线记录ID
  "cglTargetDevelopState" : '', //目标开发阶段
  "cglTargetTrackingNum" : '', //月目标有效跟进次数
  "cglTargetFinishedDate" : "" //预计完成时间
};

export default {
  name: "index",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count: 0,
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      gridOptions:{
        border: true,
        id: 'lineListPL',
        align:'center',
        showOverflow:false,
        rowConfig: {
          keyField: 'cglId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          },
          className:'mytoolbar',
        },
        spanMethod({ row, rowIndex, $rowIndex, _rowIndex, column, columnIndex, $columnIndex, _columnIndex, visibleData }){
          let fields = ['customerName']
          if(!fields.includes(column['field'])){
            return { rowspan: 1, colspan: 1 }
          }else if(row['isMerge'] && (fields.includes(column['field']))){
            return { rowspan: row['rowNum'], colspan: 1 }
          }else {
            return { rowspan: 0, colspan: 0 }
          }

        },
        columns: [

          { type: 'checkbox',
            title: '',
            fixed:'left',
            width: 50,
          },
          {
            field: 'customerName',
            title: '客户名称',
            width: 150,
            showOverflow:false,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'goodsLineName',
            title: '产品线',
            width: 150,
          },
          {
            field: 'relationCustomers',
            title: '子客户',
            showOverflow:true,
            width: 150,
          },
          {
            field: 'cglOrderNum',
            title: '成交量',
            width: 100,
          },
          {
            field: 'abutmentNum',
            title: '转售量',
            width: 100,
          },
          {
            field: 'cglOrderTime',
            title: '最近成交时间',
            width: 150,
          },
          {
            field: 'cglCurrentDevelopState',
            title: '当前阶段',
            width: 100,
          },
          {
            field: 'cglTargetDevelopState',
            title: '目标开发阶段',
            width: 100,
          },
          {
            field: 'targetStatus',
            title: '开发目标状态',
            width: 100,
          },
          {
            field: 'cglTargetTrackingNum',
            title: '月目标有效跟进次数',
            width: 100,
          },

          {
            field: 'cglActualTrackingNum',
            title: '实际月有效跟进次数',
            width: 100,
          },
          {
            field: 'trackIngStatus',
            title: '跟进状态',
            width: 100,
          },
          {
            field: 'cglTrackingTime',
            title: '最近跟进时间',
            width: 150,
          },
          {
            field: 'cglTrackingContent',
            title: '最近跟进内容',
            showOverflow:true,
            width: 150,
          },
          {
            field: 'chargeDayNum',
            title: '持有天数',
            width: 100,
          },
          {
            field: 'cglMonthBuyNum',
            title: '预计月使用量',
            width: 150,
          },
          {
            field: 'cglCustomerFocusStr',
            title: '客户关注点',
            width: 150,
          },
          {
            field: 'cglBuyHabitsStr',
            title: '采购习惯',
            width: 150,
          },
          {
            field: 'goodsMatchDegree',
            title: '产品匹配',
            width: 150,
          },
          {
            field: 'cglMyChargeTime',
            title: '负责日期',
            width: 150,
          },
          {
            field: 'cglUserName',
            title: '负责人',
            width: 100,
          },
          {
            field: 'trackingTime',
            title: '最进一次跟进距今日天数',
            width: 100,
          },
          {
            field: 'cglCustomerLabel',
            title: '标签',
            width: 100,
          },{
            field: 'createTime',
            title: '创建日期',
            width: 150,
          },{
            field: 'updateTime',
            title: '更新日期',
            width: 150,
          },
          {
            field: 'goodsSn',
            title: '使用材料',
            width: 150,
            visible: false,
          },


          {
            field: 'cglTargetFinishedDate',
            title: '预计开发完成时间',
            width: 100,
            visible: false,
          },
          {
            field: 'cglTransactionTime',
            title: '预计成交时间',
            width: 150,
            visible: false,
          },
          {
            field: 'cglPerProfit',
            title: '预计吨毛利',
            width: 100,
            visible: false,
          },
          {
            field: 'shareUserNames',
            title: '共享人',
            width: 150,
            visible: false,
          },{
            field: 'cglCompetitorInfo',
            title: '竞争对手情况',
            width: 150,
            showOverflow:true,
            visible: false,
          },{
            field: 'cglCompetitorType',
            title: '竞争对手类型',
            width: 100,
            visible: false,
          },{
            field: 'cglScale',
            title: '规模',
            width: 100,
            visible: false,
          },{
            field: 'cglOperatingRate',
            title: '开工率',
            width: 100,
            visible: false,
          },{
            field: 'cglPayMethod',
            title: '支付方式',
            width: 100,
            visible: false,
          },
          {
            field: 'takIngCount',
            title: '总跟进次数',
            width: 150,
            visible: false,
          },
          {
            field: '',
            title: '操作',
            width: 250,
            fixed:'right',
            slots: {
              // 使用插槽模板渲染
              default: 'num3_default',
            },
          },
        ],
        data:[],
      },

      querySearchList:[],
      options:[],
      customerSourceList:[],
      customerPotentialList:[],
      customerTypeList:[],
      options2:[],
      labels:[],

      title:'',
      popcon:'',
      popType:'',
      dialogVisible:false,
      btnLoading:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      userOptionList:[],
      rules:{
        target: [{required: true, message: '此项必填', trigger: 'change'},],
        remark:[{required: true, message: '此项必填', trigger: 'blur'},],
      },

      dialogVisible2:false,
      btnLoading2:false,
      form2:JSON.parse(JSON.stringify(defaultForm2)),
      rules2:{
        tagIds: [{required: true, message: '此项必填', trigger: 'change'},],
      },
      tags:[],
      myTags:[],
      dialogVisible3:false,
      btnLoading3:false,
      form3:JSON.parse(JSON.stringify(defaultForm3)),
      rules3:{
        name: [{required: true, message: '此项必填', trigger: 'blur'},],
      },

      dialogVisible4:false,
      btnLoading4:false,
      form4:JSON.parse(JSON.stringify(defaultForm4)),
      rules4:{
        name: [{required: true, message: '此项必填', trigger: 'blur'},],
      },
      goodsLineCount:'',
      goodsLineList:[],
      devStates:[{name:'超期',id:'1'},{name:'进行中',id:'2'},{name:'已完成',id:'3'}],
      developSteps:[
        {name:'全部',id:''},{name:'寻找关键人',id:10},{name:'挖掘需求',id:20},{name:'建立粘度',id:30},{name:'促成交',id:40},
      ],
      numCount:[],
      dialogVisible5:false,
      form5:JSON.parse(JSON.stringify(defaultForm4)),
      rules5:{
        cglTargetDevelopState: [{required: true, message: '此项必填', trigger: 'change'},],
        cglTargetTrackingNum: [{required: true, message: '此项必填', trigger: 'blur'},],
        cglTargetFinishedDate: [{required: true, message: '此项必填', trigger: 'blur'},],
      },
      btnLoading5:false,
      title5:'',
      pickerOptions: {
        disabledDate(time) {
          return (time.getTime() < Date.now() - 8.64e7) || (time.getTime() > Date.now() + 60*60*1000*24*60)
        }
      },
      popType5:'',
      resourceNum:'',

      btnLoading6:false,
      customerCount:0
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {
    gjList,
    lxrList,
    addLxr,
    addGj,
    addProgress,
    importPop
  },
  created() {


  },

  filters: {

  },
  methods:{
    //显导入弹窗
    showImport(){
      this.$refs.importPop.showImport('importGoodsLineTarget','导入产品线目标数据','/api/customerNew/importMyGoodsLine/download',)
    },

    //下载excle
    downloadExcel(){
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.cglCustomerLabel = params.cglCustomerLabel.join(",")
      params.chargeId = params.tab == 'myCharge' ? '' : params.chargeId;
      params.isResource = params.tab == 'myCharge' ?  params.isResource : '';
      params.myExport = 1;
      delete params.pageSize;
      delete params.pageNum;
      this.btnLoading6 = true
      goodsLineMyGoodsLine(params).then((res)=>{
        this.btnLoading6 = false
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnLoading6 = false
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    showDevPop(type,item){
         let cglIds = [];
         let records = [];
         this.popType5 = type
         if(type == 'more'){
          let list = this.$refs.lineListPLxGrid.getCheckboxReserveRecords();
          let list2 = this.$refs.lineListPLxGrid.getCheckboxRecords();
          records = JSON.parse(JSON.stringify(list.concat(list2)));
        }else{
           records.push(item)
       }
        if(records.length == 0){
          this.$message({
            type: 'info',
            message: '请先选择记录！'
          });
          return false
        }
        this.dialogVisible5 = true;
        this.title5 = type == 'more' ? '批量设置开发目标' : '设置开发目标';
        this.form5 = JSON.parse(JSON.stringify(defaultForm5));
        records.forEach((el)=>{
          cglIds.push(el.cglId)
        })
        this.form5.cglIds = cglIds.join(",");
    },

    handleConfirm5(){
      this.$refs['form5'].validate((valid) => {
        if (valid) {
          this.btnLoading5 = true;
          let data = JSON.parse(JSON.stringify(this.form5));
          if(this.popType5 == 'more'){
            delete data.cglTargetFinishedDate
          }
          developBatchSetTarget(data).then(()=>{
            this.btnLoading5 = false;
            this.dialogVisible5 = false;
            this.$refs.lineListPLxGrid.clearCheckboxRow(false);
            this.$refs.lineListPLxGrid.clearCheckboxReserve()
            this.getList()
          }).catch(()=>{
            this.btnLoading5 = false;
          })
        }
      })
    },

    toAdd(){
      this.$router.push({name:'addCustomerPL'})
    },
    showZQ(item){
      this.$refs.addProgress.showPop(item);
    },
    //显示新增跟进
    showAddgj(item){
      this.$refs.addGj.showTracking(item,'add')
    },
    //获取客户配置
    getCustomerSettingList(){
      getCustomerSetting().then((res)=>{
        res.forEach((el)=>{
          if(el.cdtCode == 'goods_line'){
            this.goodsLineList = el.data
          }
        });
      })
    },
    toDetail(item){
      let routeData = this.$router.resolve({name:'customerGoodsLineInfo',query:{id:item.customerId}});
      window.open(routeData.href);
    },
    //显示增加备注
    showPop4(){
      let list = this.$refs.lineListPLxGrid.getCheckboxReserveRecords();
      let list2 = this.$refs.lineListPLxGrid.getCheckboxRecords();
      let records = JSON.parse(JSON.stringify(list.concat(list2)));
      if(records.length == 0){
        this.$message({
          type: 'info',
          message: '请先选择记录！'
        });
        return false
      }
      this.dialogVisible4 = true;
      this.form4 = JSON.parse(JSON.stringify(defaultForm4));
      let cglIds = []
      records.forEach((el)=>{
        cglIds.push(el.cglId)
      })
      this.form4.cglIds = cglIds.join(",")
    },
    handleConfirm4(){
      this.$refs['form4'].validate((valid) => {
        if (valid) {
          this.btnLoading4 = true;
          let data = JSON.parse(JSON.stringify(this.form4));
          fn(data).then(()=>{
            this.btnLoading4 = false;
            this.dialogVisible4 = false;
            this.$refs.lineListPLxGrid.clearCheckboxRow(false);
            this.$refs.lineListPLxGrid.clearCheckboxReserve()
            this.getList()
          }).catch(()=>{
            this.btnLoading4 = false;
          })
        }
      })
    },

    //显示增加联系人
    showAddLxr(type,item){
      this.$refs.addLxr.showContact(type,item)
    },
    //显示跟进记录
    showPop2(item){
      this.$refs.gjList.showPop(item,'goodsLine')
    },
    //显示联系人
    showPop3(item){
      this.$refs.lxrList.showPop(item,'goodsLine')
    },

    //显示新建标签
    addLabel(){
      this.dialogVisible3 = true;
      this.form3 = JSON.parse(JSON.stringify(defaultForm3))
    },
    //添加标签
    handleConfirm3(){
      this.$refs['form3'].validate((valid) => {
        if (valid) {
          this.btnLoading3 = true;
          let data = JSON.parse(JSON.stringify(this.form3));
          productCustomersAddTag(data).then(()=>{
            this.btnLoading3 = false;
            this.dialogVisible3 = false;
            this.getmyAllTags();
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

    //获取标签列表
    getmyAllTags(){
      myAllTags().then((res)=>{
         this.tags = res.allList;
         this.myTags = res.myList
      })
    },

    showPop(){
      let list = this.$refs.lineListPLxGrid.getCheckboxReserveRecords();
      let list2 = this.$refs.lineListPLxGrid.getCheckboxRecords();
      let records = JSON.parse(JSON.stringify(list.concat(list2)));
      if(records.length == 0){
        this.$message({
          type: 'info',
          message: '请先选择记录！'
        });
        return false
      }
      this.dialogVisible2 = true;
      this.form2 = JSON.parse(JSON.stringify(defaultForm2));
      let cglIds = [];
      records.forEach((el)=>{
        cglIds.push(el.cglId)
      })
      this.form2.cglIds = cglIds.join(",")
    },

    //确认标签
    handleConfirm2(){
      console.log(this.$refs['form2'].validate)
      this.$refs['form2'].validate((valid) => {
        if (valid) {
           this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.form2));
          data.tagIds = this.form2.tagIds.join(",")
          addCustomerTags(data).then(()=>{
            this.btnLoading2 = false;
            this.dialogVisible2 = false;
            this.$refs.lineListPLxGrid.clearCheckboxRow(false);
            this.$refs.lineListPLxGrid.clearCheckboxReserve()
            this.getList()
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },
    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },
    //客户转移
    moveLine(type,isOne,item){
      let records = [];
      console.log("records",records)
      if( isOne != 'one'){
        let list = this.$refs.lineListPLxGrid.getCheckboxReserveRecords();
        let list2 = this.$refs.lineListPLxGrid.getCheckboxRecords();
        records = JSON.parse(JSON.stringify(list.concat(list2)));
      }else{
        records.push(item)
      }
      if(records.length == 0){
        this.$message({
          type: 'info',
          message: '请先选择记录！'
        });
        return false
      }
      this.popType = type
      switch (type){
        case 'user':
          this.title = '产品线转移';
          this.popcon = '将产品线转移动其它负责人'
          break;
        case 'resource':
          this.title = '转移到共享池';
          this.popcon = '将客户负责的产品线转移到共享池'
          break;
        case 'share':
          this.title = '设置共享';
          this.popcon = '将自己负责的客户产品线设置为共享人，共享人可以看到，设置后原共享人替换'
          break;
        case 'delete':
          this.title = '移入回收站';
          this.popcon = '将自己负责的客户产品线移入到回收站'
          break;
        case 'public':
          this.title = '转入公海';
          this.popcon = '将自己负责的客户产品线转入到公海'
          break;
      }
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm));
      let cglIds = []
      records.forEach((el)=>{
        cglIds.push(el.cglId)
      })
      this.form.cglIds = cglIds.join(",")
    },

    //确认客户转移
    handleConfirm(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          let  fn;
          switch (this.popType){
            case 'user':
              fn = goodsLineMove
              data.isTransfer = 1
              break;
            case 'resource':
              fn = commonGoodsLine
              data.target = 2;
              break;
            case 'share':
              fn = shareGoodsLine
              data.target = this.form.target.join(",")
              break;
            case 'delete':
              fn = deleteGoodsLine
              data.target = 1;
              break;
            case 'public':
              fn = commonGoodsLine
              data.target = 1;
              break;
          }
          fn(data).then(()=>{
            this.btnLoading = false;
            this.dialogVisible = false;
            this.$refs.lineListPLxGrid.clearCheckboxRow(false);
            this.$refs.lineListPLxGrid.clearCheckboxReserve()
            this.getList()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },


    init(key){
      this.listQuery.tab = key;
      this.handleSearchList();
      this.getLabels();
      this.getmyAllTags();
      this.getUserOptionList();
      this.getCustomerSettingList();
    },
    // 获取客户标签列表
    getLabels(){
      productCustomersTagList({status: 1}).then(response => {
        this.labels = response.list;
      });
    },

    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= ''){
        getCustomerOption({keywords:queryString,tab:this.listQuery.tab == 'myCharge' ? 'my' : ''}).then((res)=>{
          this.querySearchList = res;
        })
      }
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let listQuery = JSON.parse(JSON.stringify(this.listQuery))
      listQuery.cglCustomerLabel = listQuery.cglCustomerLabel.join(",")
      listQuery.chargeId = listQuery.tab == 'myCharge' ? '' : listQuery.chargeId;
      listQuery.isResource = listQuery.tab == 'myCharge' ?  listQuery.isResource : '';
      goodsLineMyGoodsLine(listQuery).then(response => {
        this.gridOptions.data = [];
        this.numCount = [];
        this.numCount.push(response.peopleCount,response.demandCount,response.relationCount,response.dealCount)
        response.list.forEach((el,i)=>{
          let newEL = JSON.parse(JSON.stringify(el));
          delete newEL.goodsLineList
          el.goodsLineList.forEach((ee,ii)=>{
            let newEE = JSON.parse(JSON.stringify(ee));
            if(ii == 0){
              console.log("ii",ii)
              newEE.isMerge = true;
              newEE.rowNum = el.goodsLineList.length;
            }else{
              newEE.isMerge = false;
              newEE.rowNum = 0;
            }
            let copy = Object.assign({},newEL,newEE);
            this.gridOptions.data.push(copy);
          })
        })
        this.count = response.count;
        this.goodsLineCount = response.goodsLineCount;
        this.resourceNum = response.resourceNum;
        this.customerCount = response.customerCount
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },

  },
}
</script>

<style  lang="scss">
.vxe-toolbar.size--mini.mytoolbar{
  height:auto
}
</style>
